import axios from 'axios'
// import { Message, MessageBox } from 'element-ui'
// import 'element-ui/lib/theme-chalk/index.css'
import Vue from 'vue'
import { ToastPlugin,LoadingPlugin, ConfirmPlugin } from 'vux'
import store from '@/store/index.js'
import getters from '@/store/getters'
import { getToken } from '@/utils/auth'
import Lockr from 'Lockr'

Vue.use(ToastPlugin, {position: 'middle', 'is-show-mask': true, time: 1500}) // toast默认参数值
Vue.use(LoadingPlugin) // 加载中插件 this.$vux.loading.show({ text: 'Loading' });  this.$vux.loading.hide()
Vue.use(ConfirmPlugin)

// 创建axios实例
Lockr.set('myRegion', {id: 1333, parent_id: 188, name: "洛阳市市辖区", level: 3, adcode: "410301", company_id: 1})
var company_dis = Lockr.get('myRegion')
// console.log(company_dis)
const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 5000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    if (getters.token) {
      config.headers['mytoken'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    config.headers['rtk'] = 'a5b8d2dfe09f21ee3a395ddbc7926f3c'//每个请求都带rtk

    if(company_dis){
        config.headers['company_id'] = company_dis.company_id
        // console.log(company_dis.company_id)
    }//每个请求都带companyid
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response.data
    // alert(JSON.stringify(res))
    if (res.code !== 1 && res.code !== 0) {

      // self.$vux.toast.show({
      //   text: res.msg,
      //   type: 'warn'
      // })

      // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        MessageBox.confirm(
          '你已被登出，可以取消继续留在该页面，或者重新登录',
          '确定登出',
          {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      }
      return Promise.reject('error')
    }else if(res.code==0){
      alert(res.msg)
      return Promise.reject('error')  
      // return response.data
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
